package com.zhida.courseservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhida.common.context.UserContext;
import com.zhida.common.entity.Result;
import com.zhida.courseservice.entity.Course;
import com.zhida.courseservice.mapper.CourseMapper;
import com.zhida.courseservice.service.ICourseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.apache.commons.lang.ObjectUtils;
import org.springframework.stereotype.Service;

import static com.zhida.common.utils.RegexUtil.ROOT_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ling
 * @since 2024-07-17
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {

    @Resource
    CourseMapper courseMapper;

    @Override
    public Result<?> createCourse(Course course) {
        course.setCourseOwner(UserContext.getUser());
        course.setCourseOwner(UserContext.getUser());
        courseMapper.insert(course);
        return Result.success("发布成功");
    }

    @Override
    public Result<?> getCourseInfo(Integer courseId) {
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id",courseId);
        Course course = courseMapper.selectOne(queryWrapper);
        if (course != null){
            return Result.success(course);
        }
        return Result.error404("未查询到该课程信息");
    }

    @Override
    public Result<?> updateCourseInfo(Course course) {
//        判断是否有权限更改
        if (!ROOT_KEY.equals(UserContext.getUser())){
            return Result.error403("无权限操作课程更新");
        }
        if (courseMapper.updateById(course) == 1){
            return Result.successMsg("更新成功");
        }
        return Result.error404("更新失败");
    }

    @Override
    public Result<?> getCourses(Integer current, Integer pageSize) {
        Page<Course> page = new Page<>(current,pageSize);
        return Result.success(courseMapper.selectPage(page,null));
    }
}
